<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Random;
use EasyWeChat\Factory;
use app\common\model\User;
/**
 * Token接口
 */
class Wechat extends Api
{
    protected $app;
    protected $config;
    protected $noNeedLogin = ['login', 'saveUserInfo'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        // 这里的配置信息可以写入基本配置里面，这里只是为了练手
        $this->config = [
            'app_id' => 'wxee36cf85ac175bdd',
            'secret' => 'd9d902736f89b7ef32a70db2889f62cd',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file'  =>  ROOT_PATH . '/public/logs/wxMiniProgramLogin.log'
            ]
        ];

        $this->app = Factory::miniProgram($this->config);
    }

    # 根据code获取sessionKey和openId
    public function login()
    {
        $code = $this->request->post('code');

        if (!$code) {
            $this->error('缺少必要参数code');
        }

        $result = $this->app->auth->session($code);

        /* $result 输出结果
         * Array (
            [session_key] => 0mZrSFu1K6vX7appQsrxOw==
            [openid]      => ooOoU5a6Ulb0-bXZqjlWsZowwVRc
        )*/

        if (!$result) {
            $this->error('获取sessionKey和openId时异常');
        }

        if (!empty($result['errcode']) && $result['errcode'] != 0) {
            return ['code' => $result['errcode'], 'msg' => $result['errmsg']];
        }

        $this->success('获取信息成功', $result);
    }

    /* login() 输出结果
     * {
        "code":1,
        "msg":"获取信息成功",
        "time":"1619163984",
        "data":{
            "session_key":"3uh+wLzDl47zHOEj4H4fSg==",
            "openid":"ooOoU5a6Ulb0-bXZqjlWsZowwVRc"
        }
    }*/

    # 获取用户基本信息
    public function saveUserInfo()
    {
        $params = $this->request->post();
        // 入参
        extract($params);
        if (empty($iv) || empty($openid) || empty($sessionKey) || empty($encryptedData)) {
            $this->error('缺少必要参数！');
        }
        $result = $this->app->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        /* $result 输出结果
         * Array (
            [nickName]  => 霍文霆
            [gender]    => 1
            [language]  => zh_CN
            [city]      =>
            [province]  => Anhui
            [country]   => China
            [avatarUrl] => https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIwdDXLgfezLpDudf6gu0yD2VBE7dHgiaGFWT2HwRcNuN9paUSlCvPWaQtOSOPHpLtRxKzK7DtJiaHQ/132
            [watermark] => Array (
                [timestamp] => 1619163984
                [appid]     => wx53ce5308043dcd53
            )
        )*/
        $user = User::get(['openid' => $openid]);
        if (!empty($user)) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            // 更新用户数据
            $user->nickname = base64_decode(base64_encode($result['nickName']));
            $user->avatar = $result['avatarUrl'];
            $user->save();
            // 直接登陆
            $ret = $this->auth->direct($user->id);
        } else {
            // 拉起小程序登录
            $ret = $this->auth->wxMiniProgramLogin($result,$openid);
        }
        if ($ret) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败');
        }
    }
}
